<!-- 通用组件 - 树形选择器 -->
<template>
	<div>
		
		<el-dialog
			title="选择"
			:visible.sync="dialogVisible"
			:modal="false">

			<el-input v-model="keyword" 
				size="small"
				prefix-icon="el-icon-search"
				style="display:inline-block; width:200px; margin: 0 0 10px 10px;">
			</el-input>

			<div class="_tree" style="height: 300px; overflow-y: scroll;">
				<el-tree 
					ref="tree"
					show-checkbox
					node-key="id"
					:data="data" 
					:props="defaultProps" 
					:check-strictly="true"
					:check-on-click-node="true"
					@check="onCheckChange"
					:filter-node-method="filt"
				></el-tree>
			</div>

			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="ok()">确 定</el-button>
			</span>
		</el-dialog>

	</div>
</template>

<script>
export default {
	props: ['dataUrl', 'multi', 'dynamic'], // 数据请求地址, 是否可多选(默认false)
	data() {
		return {
			dialogVisible: false,
			data: [],
			defaultProps: {
				children: 'children',
				label: 'label'
			},
			keyword: ''
		}
	},
	created: function() {
		if(!this.dynamic) {
			this.getData();
		}
	},
	watch: {
		keyword: function(val) {
			this.$refs['tree'].filter(val);
		}
	},
	methods: {
		open: function() {
			this.dialogVisible = true;
			if(this.dynamic) {
				this.getData();
			}
		},
		getData: function() {
			var that = this;
			this.$axios.get(this.dataUrl).then(resp => {
				that.data = this.transData(resp.data, 'id', 'pid', 'children');
			});
		},
		onCheckChange(data, b) {
			if(!this.multi) {
				if(b.checkedKeys.length > 0){
						this.$refs.tree.setCheckedKeys([data.id]);
				}
			}
		},
		filt: function(val, data) {
			if(!val) {
				return true;
			}
			return data.label.indexOf(val) > -1;
		},
		// 数据结构转换: 将 id/pid 的形式, 转化为 children 的形式
		transData: function(a, idStr, pidStr, chindrenStr) {
			var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;
			for(; i < len; i++) {
				hash[a[i][id]] = a[i];
			}
			for(; j < len; j++) {
				var aVal = a[j], hashVP = hash[aVal[pid]];
				if(hashVP) {
						!hashVP[children] && (hashVP[children] = []);
						hashVP[children].push(aVal);
				}else {
						r.push(aVal);
				}
			}
			return r;
		},
		ok: function() {
			var nodes = this.$refs.tree.getCheckedNodes();
			var nodes2 = [];
			nodes.forEach(element => {
				nodes2.push(element);
			});
			// 未勾选时
			if(nodes2.length == 0) {
				nodes2.push({id:'', label: ''});
			}
			this.dialogVisible = false;
			this.$emit('on_ok', nodes2);
		}
	}
}
</script>

<style>
</style>